<template>
  <div ref="echartRef" class="echarts_container"></div>
</template>

<script setup>
import * as echarts from 'echarts'
import { onMounted, ref, shallowRef, watch, defineProps, defineEmits } from 'vue'

// 定义 emits，用于向父组件传递点击事件
const emit = defineEmits(['barchartClick'])

// 定义props
const props = defineProps({
  chartType: {
    type: String,
    default: ''
  },
  labelFontsize: {
    type: Number,
    default: 16
  },
  titleName: {
    type: String,
    default: ''
  },
  xAxisName: {
    type: String,
    default: ''
  },
  xAxisData: {
    type: Array,
    default: () => []
  },
  yAxisName: {
    type: String,
    default: ''
  },
  yAxisData: {
    type: Array,
    default: () => []
  }
})
const echartRef = ref(null)
let chartInstance = shallowRef(null)

let theOption = {
  title: {
    text: props.titleName,
    textStyle: {
      color: '#fff',
      textBorderColor: '#ffff00',
      textBorderWidth: 1
    }
  },
  tooltip: {},
  xAxis: {
    data: props.xAxisData,
    axisLabel:{
      color: '#ffff00',
      fontSize: props.chartFontsize
    }
  },
  yAxis: {
    axisLabel:{
      color: '#ffff00',
      fontSize: props.chartFontsize
    }
  },
  series: [
    {
      name: props.yAxisName,
      type: 'line',
      color: '#ff00ff',
      data: props.yAxisData
    },
    {
      name: props.yAxisName,
      type: 'bar',
      color: '#aaffff',
      emphasis: {
        itemStyle: {
          color: '#ffabcd'
        }
      },
      data: props.yAxisData
    }
  ]
}
function handleChartInit(params){
  console.log('barchartClick params', params);
  
  emit('barchartClick', params)
  // 取消所有柱的高亮
  // chartInstance.value.dispatchAction({
  //   type: 'downplay',
  //   seriesIndex: 1
  // })
  // 高亮点击的柱
  // chartInstance.value.dispatchAction({
  //   type: 'highlight',
  //   dataIndex: 0
  // })
  
}
function handleChartClick(params){
  console.log('barchartClick params', params);
  
  emit('barchartClick', params)
  // 获取点击的柱状图的索引
  let dataIndex = params.dataIndex
  // 取消所有柱的高亮
  chartInstance.value.dispatchAction({
    type: 'downplay',
    seriesIndex: 1
  })
  // 高亮点击的柱
  chartInstance.value.dispatchAction({
    type: 'highlight',
    dataIndex: dataIndex
  })
  console.log('dataIndex', dataIndex);
  
}

onMounted(() => {
  handleChartInit({
    name: '2014',
    dataIndex: 0
  })
  if (echartRef.value) {
    chartInstance.value = echarts.init(echartRef.value)
    chartInstance.value.setOption(theOption, true)
    chartInstance.value.on('click', handleChartClick)
  }
})
watch(
  () => props.xAxisData,
  (newOptions) => {
    theOption.xAxis.data = newOptions
    chartInstance.value.setOption(theOption, true)
  },
  { deep: true }
)
window.addEventListener('resize', () => {
  if (chartInstance.value) {
    chartInstance.value.resize()
  }
})
</script>

<style lang="scss" scoped>
.echarts_container {
  width: 100vw;
  height: 100vh;
}
</style>
